<?php
declare (strict_types = 1);

namespace app\middleware;

use Firebase\JWT\JWT as JWTUtil;

class Jwt
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        //
        $token = $request->header('authorization');
        $res = self::verifyJwt($token);
        if($res['status']!=1001){
            return $res;
        }
            
        return $next($request);
    }

    //校验jwt权限API
    static function verifyJwt($jwt = '')
    {
        $key = md5('zq8876!@!');
        try {
            $jwtAuth = json_encode(JWTUtil::decode($jwt, $key, ['HS256']));
            $authInfo = json_decode($jwtAuth, true);
            $msg = [];
            if (!empty($authInfo['user_id'])) {
                $msg = [
                    'status' => 1001,
                    'msg' => 'Token验证通过'
                ];
            } else {
                $msg = [
                    'status' => 1002,
                    'msg' => 'Token验证不通过,用户不存在'
                ];
            }
            return $msg;
        }  catch (\Firebase\JWT\ExpiredException $e) {
            echo json_encode([
                'status' => 1003,
                'msg' => 'Token过期'
            ]);
            exit;
        } catch (\Exception $e) {
            echo json_encode([
                'status' => 1002,
                'msg' => 'Token无效'
            ]);
            exit;
        }
    }
}
